#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : wupeiqi_async
@File : async_iterator.py
@Author : Royce
@Time : 2025/7/13 11:09  
@脚本说明 : 
"""
import asyncio

from util.util import timer


class Reader(object):
    """ 自定义异步迭代器（同时也是异步可迭代对象） """

    def __init__(self):
        self.count = 0

    async def readline(self):
        # await asyncio.sleep(1)
        self.count += 1
        if self.count == 100:
            return None
        return self.count

    @timer('ms')
    def __aiter__(self):
        return self

    @timer('ms')
    async def __anext__(self):
        val = await self.readline()
        if val == None:
            raise StopAsyncIteration
        return val


@timer('ms')
async def func():
    # 创建异步可迭代对象
    async_iter = Reader()
    # async for 必须要放在async def函数内，否则语法错误。
    async for item in async_iter:
        print(item)


if __name__ == '__main__':
    asyncio.run(func())
